package com.caocaog.market.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caocaog.market.entity.ShopMemberBind;
import com.caocaog.market.mapper.CcptMemberMapper;
import com.caocaog.market.mapper.ShopMemberBindMapper;
import com.caocaog.market.service.ShopMemberBindService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.CheckFailedException;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
 * 店铺与账号绑定
 *
 * @author chechen
 * @date 2021-11-21
 */
@Service
@RequiredArgsConstructor
public class ShopMemberBindServiceImpl extends ServiceImpl<ShopMemberBindMapper, ShopMemberBind> implements ShopMemberBindService {

    private final RedisUtil redisUtil;
    @Autowired
    private CcptMemberMapper ccptMemberMapper;
    @Override
    public ShopMemberBind queryShopMemberBindByShopId(String shopId) {
        ShopMemberBind memberBind = super.baseMapper.selectOne(new LambdaQueryWrapper<ShopMemberBind>()
                .eq(ShopMemberBind::getShopId, shopId));
        if(null!= memberBind && null!=memberBind.getPtId() && memberBind.getPtId()>0){
            BigDecimal ccptMemberBalance = ccptMemberMapper.findCcptMemberBalanceBySid(memberBind.getPtId());
            memberBind.setCcptBalance(String.valueOf(ccptMemberBalance));
            System.out.println("门店id="+shopId+"  -- 跑腿账号余额= "+ccptMemberBalance);
        }
        return memberBind;
    }

    @Override
    public String addShopMemberBind(String code, ShopMemberBind shopMemberBind) {
        JSONObject memberLoginName = universalCheck(code, shopMemberBind);
        // 注意：曹操来了多个店铺   可以   绑定   曹操跑腿中的同一个账号——————李广  2022-01-12 19：52
        ShopMemberBind isShopBind = super.baseMapper.selectOne(new LambdaQueryWrapper<ShopMemberBind>()
                .eq(ShopMemberBind::getShopId, shopMemberBind.getShopId()));
        if (isShopBind != null && StringUtils.isNotBlank(isShopBind.getId()))
            throw new JeecgBootException("此店铺已绑定账号, 店铺已绑定的账号-> " + isShopBind.getPtLoginName());

        // 新增前处理一下数据
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        shopMemberBind.setMerchantId(loginUser.getMerchantId());
        shopMemberBind.setCreateBy(loginUser.getUsername());
        shopMemberBind.setCreateTime(new Date());
        shopMemberBind.setDelFlag(CommonConstant.DEL_FLAG_0);
        shopMemberBind.setLockVersion(1);
        shopMemberBind.setPtId(memberLoginName.getInteger("sid"));
        super.baseMapper.insert(shopMemberBind);
        if (shopMemberBind.getId() == null)
            throw new JeecgBootException("店铺与账号绑定失败");
        return shopMemberBind.getId();
    }

    @Override
    public int updateShopMemberBind(String code, ShopMemberBind shopMemberBind) {
        JSONObject memberLoginName = universalCheck(code, shopMemberBind);
        // 更新前处理一下数据
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        shopMemberBind.setMerchantId(loginUser.getMerchantId());
        shopMemberBind.setUpdateBy(loginUser.getUsername());
        shopMemberBind.setUpdateTime(new Date());
        shopMemberBind.setDelFlag(CommonConstant.DEL_FLAG_0);
        shopMemberBind.setLockVersion(1);
        shopMemberBind.setPtId(memberLoginName.getInteger("sid"));
        int updateRecordCount = super.baseMapper.updateById(shopMemberBind);
        if (updateRecordCount == 0)
            throw new JeecgBootException("更新店铺绑定账号失败, id-> " + shopMemberBind.getId());
        return updateRecordCount;
    }

    @Transactional
    @Override
    public int untieShopMemberBind(String shopId) {
        int untiesRecordCount = super.baseMapper.delete(
                new LambdaQueryWrapper<ShopMemberBind>().eq(ShopMemberBind::getShopId, shopId));
        if (untiesRecordCount == 0)
            throw new JeecgBootException("店铺解绑账号失败, shopId-> " + shopId);
        return untiesRecordCount;
    }

    /**
     * 通用校验
     *
     * @param shopMemberBind 待校验的实体
     * @return cc_member的id和loginName
     */
    private JSONObject universalCheck(String smsCode, ShopMemberBind shopMemberBind) {
        Object code = redisUtil.get(shopMemberBind.getPtLoginName());
        if (!smsCode.equals(code)) {
            throw new CheckFailedException("验证码错误");
        } else redisUtil.del(shopMemberBind.getPtLoginName());
        if (StringUtils.isBlank(shopMemberBind.getPtLoginName()))
            throw new CheckFailedException("要绑定的账号不能为空");
        if (StringUtils.isBlank(shopMemberBind.getShopId()))
            throw new CheckFailedException("要绑定的店铺id (shopId) 不能为空");

        JSONObject memberLoginName = super.baseMapper.getMemberLoginName(shopMemberBind.getPtLoginName());
        if (memberLoginName == null)
            throw new JeecgBootException("未查询到有此跑腿账号, 请重新填写");
//  注意：曹操来了多个店铺   可以   绑定   曹操跑腿中的同一个账号——————李广  2022-01-12 19：52
//        ShopMemberBind isLoginNameBind = super.baseMapper.selectOne(new LambdaQueryWrapper<ShopMemberBind>()
//                .eq(ShopMemberBind::getPtLoginName, shopMemberBind.getPtLoginName()));
//        if (isLoginNameBind != null && StringUtils.isNotBlank(isLoginNameBind.getId()))
//            throw new JeecgBootException("此账号已绑定店铺, 账号已绑定的shopId-> " + isLoginNameBind.getShopId());

        return memberLoginName;
    }

}
